<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择商品分类" clearable>
          <el-option
            v-for="category in categoryList"
            :key="category.categoryId"
            :label="category.categoryName"
            :value="category.categoryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker
          v-model="queryParams.startDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开始日期"
          clearable
        />
      </el-form-item>
      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker
          v-model="queryParams.endDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束日期"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card class="statistics-card">
          <div class="statistics-item">
            <div class="statistics-value">{{ statistics.totalSaleAmount || 0 }}</div>
            <div class="statistics-label">总销售额（元）</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card">
          <div class="statistics-item">
            <div class="statistics-value">{{ statistics.totalSaleQuantity || 0 }}</div>
            <div class="statistics-label">总销售数量</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card">
          <div class="statistics-item">
            <div class="statistics-value">{{ statistics.avgGrossProfitRate || 0 }}%</div>
            <div class="statistics-label">平均毛利率</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card">
          <div class="statistics-item">
            <div class="statistics-value">{{ statistics.avgRefundRate || 0 }}%</div>
            <div class="statistics-label">平均退货率</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['statistics:good_analyse:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 报表数据表格 -->
    <el-table v-loading="loading" :data="reportList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品ID" align="center" prop="productId" width="80" />
      <el-table-column label="商品名称" align="center" prop="productName" min-width="150" show-overflow-tooltip />
      <el-table-column label="SKU编码" align="center" prop="skuCode" width="120" />
      <el-table-column label="商品分类" align="center" prop="categoryName" width="120" />
      <el-table-column label="销售数量" align="center" prop="saleQuantity" width="100">
        <template slot-scope="scope">
          <span class="number-highlight">{{ scope.row.saleQuantity || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售金额（元）" align="center" prop="saleAmount" width="120">
        <template slot-scope="scope">
          <span class="amount-highlight">{{ formatAmount(scope.row.saleAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退货数量" align="center" prop="refundQuantity" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.refundQuantity || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退货率" align="center" prop="refundRate" width="100">
        <template slot-scope="scope">
          <span :class="getRefundRateClass(scope.row.refundRate)">
            {{ formatPercentage(scope.row.refundRate) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="毛利率" align="center" prop="grossProfitRate" width="100">
        <template slot-scope="scope">
          <span :class="getProfitRateClass(scope.row.grossProfitRate)">
            {{ formatPercentage(scope.row.grossProfitRate) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="库存周转率" align="center" prop="inventoryTurnoverRate" width="120">
        <template slot-scope="scope">
          <span>{{ formatDecimal(scope.row.inventoryTurnoverRate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 商品详情对话框 -->
    <el-dialog title="商品销售详情" :visible.sync="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border v-if="detailData">
        <el-descriptions-item label="商品ID">{{ detailData.productId }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ detailData.productName }}</el-descriptions-item>
        <el-descriptions-item label="SKU编码">{{ detailData.skuCode }}</el-descriptions-item>
        <el-descriptions-item label="商品分类">{{ detailData.categoryName }}</el-descriptions-item>
        <el-descriptions-item label="销售数量">{{ detailData.saleQuantity || 0 }}</el-descriptions-item>
        <el-descriptions-item label="销售金额">{{ formatAmount(detailData.saleAmount) }}元</el-descriptions-item>
        <el-descriptions-item label="退货数量">{{ detailData.refundQuantity || 0 }}</el-descriptions-item>
        <el-descriptions-item label="退货率">{{ formatPercentage(detailData.refundRate) }}</el-descriptions-item>
        <el-descriptions-item label="成本金额">{{ formatAmount(detailData.costAmount) }}元</el-descriptions-item>
        <el-descriptions-item label="毛利率">{{ formatPercentage(detailData.grossProfitRate) }}</el-descriptions-item>
        <el-descriptions-item label="平均库存">{{ formatAmount(detailData.averageStock) }}</el-descriptions-item>
        <el-descriptions-item label="库存周转率">{{ formatDecimal(detailData.inventoryTurnoverRate) }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSalesReportList, getSalesReportDetail, getSalesReportStatistics, exportSalesReport } from "@/api/statistics/salesReport"
import { listCategory } from "@/api/fun/category"

export default {
  name: "SalesReport",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报表数据
      reportList: [],
      // 分类列表
      categoryList: [],
      // 统计数据
      statistics: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      detailOpen: false,
      // 详情数据
      detailData: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        categoryId: null,
        startDate: null,
        endDate: null
      }
    };
  },
  created() {
    this.getList();
    this.getCategoryList();
    this.getStatistics();
  },
  methods: {
    /** 查询报表列表 */
    getList() {
      this.loading = true;
      getSalesReportList(this.queryParams).then(response => {
        this.reportList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询分类列表 */
    getCategoryList() {
      listCategory().then(response => {
        this.categoryList = response.rows || [];
      });
    },
    /** 查询统计数据 */
    getStatistics() {
      const params = {
        startDate: this.queryParams.startDate,
        endDate: this.queryParams.endDate,
        categoryId: this.queryParams.categoryId,
        productName: this.queryParams.productName
      };
      getSalesReportStatistics(params).then(response => {
        this.statistics = response.data || {};
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getStatistics();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.loading = true;
      getSalesReportDetail(row.productId).then(response => {
        this.detailData = response.data;
        this.detailOpen = true;
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('statistics/good_analyse/sale/export', {
        ...this.queryParams
      }, `商品销售报表_${new Date().getTime()}.xlsx`);
    },
    /** 格式化金额 */
    formatAmount(amount) {
      if (amount == null || amount === '') return '0.00';
      return parseFloat(amount).toFixed(2);
    },
    /** 格式化百分比 */
    formatPercentage(value) {
      if (value == null || value === '') return '0.00%';
      return parseFloat(value).toFixed(2) + '%';
    },
    /** 格式化小数 */
    formatDecimal(value) {
      if (value == null || value === '') return '0.00';
      return parseFloat(value).toFixed(2);
    },
    /** 获取退货率样式类 */
    getRefundRateClass(rate) {
      if (rate == null) return '';
      const numRate = parseFloat(rate);
      if (numRate > 10) return 'high-refund-rate';
      if (numRate > 5) return 'medium-refund-rate';
      return 'low-refund-rate';
    },
    /** 获取毛利率样式类 */
    getProfitRateClass(rate) {
      if (rate == null) return '';
      const numRate = parseFloat(rate);
      if (numRate > 30) return 'high-profit-rate';
      if (numRate > 15) return 'medium-profit-rate';
      return 'low-profit-rate';
    }
  }
};
</script>

<style scoped>
.statistics-cards {
  margin-bottom: 20px;
}

.statistics-card {
  text-align: center;
}

.statistics-item {
  padding: 10px;
}

.statistics-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.statistics-label {
  font-size: 14px;
  color: #666;
}

.number-highlight {
  color: #409EFF;
  font-weight: bold;
}

.amount-highlight {
  color: #67C23A;
  font-weight: bold;
}

.high-refund-rate {
  color: #F56C6C;
  font-weight: bold;
}

.medium-refund-rate {
  color: #E6A23C;
  font-weight: bold;
}

.low-refund-rate {
  color: #67C23A;
  font-weight: bold;
}

.high-profit-rate {
  color: #67C23A;
  font-weight: bold;
}

.medium-profit-rate {
  color: #E6A23C;
  font-weight: bold;
}

.low-profit-rate {
  color: #F56C6C;
  font-weight: bold;
}
</style>